import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/LoginView.vue'),
        meta: { requiresAuth: false }
    },
    {
        path: '/',
        component: () => import('@/layouts/DefaultLayout.vue'),
        meta: { requiresAuth: true },
        children: [
            {
                path: '',
                redirect: '/workflow'
            },
            {
                path: '/workflow',
                name: 'workflow',
                component: () => import('@/views/WorkflowView.vue')
            },
            {
                path: '/workflow/create',
                name: 'workflow-create',
                component: () => import('@/views/WorkflowCreateView.vue')
            },
            {
                path: '/workflow/:id/edit',
                name: 'workflow-edit',
                component: () => import('@/views/WorkflowEditView.vue'),
                meta: { requiresAuth: true }
            }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

    // 如果页面需要认证
    if (requiresAuth) {
        // 检查是否有token
        if (!userStore.token) {
            next({ name: 'login' })
            return
        }

        // 如果没有用户信息，尝试获取
        if (!userStore.userId) {
            try {
                await userStore.getUserInfo()
            } catch (error) {
                next({ name: 'login' })
                return
            }
        }
    }

    // 如果已登录且访问登录页，重定向到首页
    if (to.name === 'login' && userStore.token) {
        next({ path: '/' })
        return
    }

    next()
})

export default router 